package org.light.simpleauth.verb;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.light.core.Verb;
import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.Dropdown;
import org.light.domain.Field;
import org.light.domain.FieldSerialComparator;
import org.light.domain.JavascriptBlock;
import org.light.domain.JavascriptMethod;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.Type;
import org.light.easyui.EasyUIPositions;
import org.light.exception.ValidateException;
import org.light.utils.FieldUtil;
import org.light.utils.StringUtil;
import org.light.utils.WriteableUtil;
import org.light.verb.FindById;

public class UpdateMyProfileUser extends Verb implements EasyUIPositions {

	@Override
	public Method generateDaoImplMethod() throws Exception {
		return null;
	}	

	@Override
	public Method generateDaoMethodDefinition() throws Exception {
		return null;
	}

	@Override
	public Method generateServiceMethodDefinition() throws Exception {
		return null;
	}

	@Override
	public Method generateServiceImplMethod() throws Exception  {
		return null;
	}
	
	public UpdateMyProfileUser(Domain domain,Set<Field> deniedFields) throws ValidateException{
		super();
		this.domain = domain;
		this.deniedFields = deniedFields;
		this.setVerbName("UpdateMyProfile"+StringUtil.capFirst(this.domain.getStandardName()));
		this.setLabel("更新自己资料");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("Update My Profile User");
	}

	@Override
	public Method generateControllerMethod() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName(StringUtil.lowerFirst(this.getVerbName()));
			method.addSignature(new Signature(1,"headers","HeaderMap"));
			method.addSignature(new Signature(2,"session","ReadableSession"));
			method.addSignature(new Signature(3,"Json("+StringUtil.getSnakeName(this.domain.getStandardName())+"_request)","Json<"+this.domain.getCapFirstDomainName()+"Request>"));
			method.setReturnType(new Type("String"));
			FindUserShadow findShadow0 = new FindUserShadow(this.domain,this.domain.getDbType());
			
			Set<Field> deniedFields = new TreeSet<>();
			deniedFields.add(this.domain.findFieldByFixedName("password"));
			deniedFields.add(this.domain.findFieldByFixedName("salt"));
			deniedFields.add(this.domain.findFieldByFixedName("loginFailure"));
			
			List<Writeable> sList = new ArrayList<Writeable>();
			long serial = 1000L;
			
			sList.add(new Statement(1000L,1,"let stoken:std::option::Option<String> = session.get(\"token\");"));
			sList.add(new Statement(1100L,1,"let mut token:String = \"\".to_string();"));
			sList.add(new Statement(1200L,1,"match stoken {"));
			sList.add(new Statement(1300L,2,"Some(stoken) => {"));
			sList.add(new Statement(1400L,3,"token = stoken;"));
			sList.add(new Statement(1500L,2,"},"));
			sList.add(new Statement(1600L,2,"None => {"));
			sList.add(new Statement(1700L,3,"token =  headers.get(\"X-Token\").unwrap().to_str().unwrap().to_string();"));
			sList.add(new Statement(1800L,2,"}"));
			sList.add(new Statement(1900L,1,"}"));
			
			sList.add(new Statement(serial+3000L,1,"let claims:Claims = jsonwebtoken::decode("));
			sList.add(new Statement(serial+4000L,2,"&token,"));
			sList.add(new Statement(serial+5000L,2,"&DecodingKey::from_secret(JWT_SECRET.as_bytes()),"));
			sList.add(new Statement(serial+6000L,2,"&Validation::default(),"));
			sList.add(new Statement(serial+7000L,1,")"));
			sList.add(new Statement(serial+8000L,1,".map(|data| data.claims).unwrap();"));
			FindById find0 = new FindById(this.domain);
			sList.add(new Statement(serial+10000L,1,"let old_"+this.domain.getSnakeDomainName()+" = service_"+StringUtil.getSnakeName(find0.getVerbName())+"(claims.sub).await.unwrap();"));

			serial += 11000L;
			for (Field f: this.domain.getFieldsWithoutId()) {
				if (!deniedFields.contains(f)) {
					if (!"Image".equalsIgnoreCase(f.getFieldType())) {
						if ("datetime".equalsIgnoreCase(f.getFieldType())) {
							sList.add(new Statement(serial,1,"let "+f.getSnakeFieldName()+" = "+this.domain.getSnakeDomainName()+"_request."+f.getSnakeFieldName()+".unwrap_or_default();"));
							sList.add(new Statement(serial+100L,1,"let mut _fmt_"+f.getSnakeFieldName()+" = Option::None;"));
							sList.add(new Statement(serial+200L,1,"if "+f.getSnakeFieldName()+" != \"\" {"));
							sList.add(new Statement(serial+300L,2,"_fmt_"+f.getSnakeFieldName()+" = Some(NaiveDateTime::parse_from_str(&"+f.getSnakeFieldName()+",DATE_TIME_FORMAT).unwrap());"));
							sList.add(new Statement(serial+400L,1,"}"));
						}else if ("date".equalsIgnoreCase(f.getFieldType())) {
							sList.add(new Statement(serial,1,"let "+f.getSnakeFieldName()+" = "+this.domain.getSnakeDomainName()+"_request."+f.getSnakeFieldName()+".unwrap_or_default();"));
							sList.add(new Statement(serial+100L,1,"let mut _fmt_"+f.getSnakeFieldName()+" = Option::None;"));
							sList.add(new Statement(serial+200L,1,"if "+f.getSnakeFieldName()+" != \"\" {"));
							sList.add(new Statement(serial+300L,2,"_fmt_"+f.getSnakeFieldName()+" = Some(NaiveDate::parse_from_str(&"+f.getSnakeFieldName()+",DATE_FORMAT).unwrap());"));
							sList.add(new Statement(serial+400L,1,"}"));
						} else {
							sList.add(new Statement(serial,1,"let "+f.getSnakeFieldName()+" = "+this.domain.getSnakeDomainName()+"_request."+f.getSnakeFieldName()+".unwrap_or_default();"));
						}
						serial += 1000L;
					}
				}
			}
			
			FindUserShadow findShadow = new FindUserShadow(this.domain,this.domain.getDbType());
			sList.add(new Statement(serial+1000L,1,"let ori_"+this.domain.getSnakeDomainName()+" = service_"+StringUtil.getSnakeName(findShadow.getVerbName())+"(old_"+this.domain.getSnakeDomainName()+"."+this.domain.findFieldByFixedName("userName").getSnakeFieldName()+".clone()).await.unwrap();"));
			sList.add(new Statement(serial+2000L,1,"let "+this.domain.findFieldByFixedName("salt").getSnakeFieldName()+" = ori_"+this.domain.getSnakeDomainName()+"."+this.domain.findFieldByFixedName("salt").getSnakeFieldName()+";"));
			sList.add(new Statement(serial+3000L,1,"let "+this.domain.findFieldByFixedName("loginFailure").getSnakeFieldName()+" = ori_"+this.domain.getSnakeDomainName()+"."+this.domain.findFieldByFixedName("loginFailure").getSnakeFieldName()+";"));
			sList.add(new Statement(serial+4000L,1,"let "+this.domain.findFieldByFixedName("password").getSnakeFieldName()+" = ori_"+this.domain.getSnakeDomainName()+"."+this.domain.findFieldByFixedName("password").getSnakeFieldName()+";"));
			
			FindById find = new FindById(this.domain);
			sList.add(new Statement(serial+5000L,1,"let _current_"+this.domain.getSnakeDomainName()+" = service_"+StringUtil.getSnakeName(find.getVerbName())+"(old_"+this.domain.getSnakeDomainName()+"."+this.domain.getDomainId().getSnakeFieldName()+".clone()).await.unwrap();"));
			serial += 6000L;
			for (Field f: this.domain.getFields()) {
				if ("Image".equalsIgnoreCase(f.getFieldType())) {
					sList.add(new Statement(serial+2000L,1,"let current_"+f.getSnakeFieldName()+" = _current_"+this.domain.getSnakeDomainName()+"."+f.getSnakeFieldName()+";"));
					sList.add(new Statement(serial+3000L,1,"let mut my_"+f.getSnakeFieldName()+" = pick_"+this.domain.getSnakeDomainName()+"_picture(\""+f.getSnakeFieldName()+"\".to_string());"));
					sList.add(new Statement(serial+4000L,1,"if my_"+f.getSnakeFieldName()+".len() == 0 && current_"+f.getSnakeFieldName()+".len()>0 {"));
					sList.add(new Statement(serial+5000L,2,"my_"+f.getSnakeFieldName()+" = current_"+f.getSnakeFieldName()+";"));
					sList.add(new Statement(serial+6000L,1,"}"));
					serial += 7000L;
				}
			}			
			
			sList.add(new Statement(serial,0,""));
			sList.add(new Statement(serial+1000L,1,"let "+this.domain.getSnakeDomainName()+" = "+this.domain.getCapFirstDomainNameWithSuffix()+"{"));
			
			sList.add(new Statement(serial+2000L,1,""+this.domain.getDomainId().getSnakeFieldName()+" : old_"+this.domain.getSnakeDomainName()+ "."+this.domain.getDomainId().getSnakeFieldName()+","));
			serial += 3000L;
			for (Field f: this.domain.getFieldsWithoutId()) {
				if (!"Image".equalsIgnoreCase(f.getFieldType())) {
					if ("datetime".equalsIgnoreCase(f.getFieldType())) {
						sList.add(new Statement(serial,1,""+f.getSnakeFieldName()+" : _fmt_"+f.getSnakeFieldName()+","));
					} else if ("date".equalsIgnoreCase(f.getFieldType())) {
						sList.add(new Statement(serial,1,""+f.getSnakeFieldName()+" : _fmt_"+f.getSnakeFieldName()+","));
					} else {
						sList.add(new Statement(serial,1,""+f.getSnakeFieldName()+" : "+f.getSnakeFieldName()+","));
					}
				}else {
					sList.add(new Statement(serial,1,""+f.getSnakeFieldName()+" : my_"+f.getSnakeFieldName()+","));
				}
				serial += 1000L;
			}
			sList.add(new Statement(serial,1,"};"));
			sList.add(new Statement(serial+1000L,1,""));
			
			UpdateUser update = new UpdateUser(this.domain);
			sList.add(new Statement(serial+19000L,1,"let _result = service_"+StringUtil.getSnakeName(update.getVerbName())+"("+this.domain.getSnakeDomainName()+").await;"));
			sList.add(new Statement(serial+20000L,1,"match _result {"));
			sList.add(new Statement(serial+21000L,2,"Err(_) => {"));
			sList.add(new Statement(serial+23000L,3,"r#\"{  \"rows\": null,  \"success\": true}\"#.to_string()"));
			sList.add(new Statement(serial+24000L,2,"},"));
			sList.add(new Statement(serial+25000L,2,"Ok(_result) => {"));
			sList.add(new Statement(serial+26000L,3,"let mut map = Map::new();"));
			sList.add(new Statement(serial+27000L,3,"map.insert(\"success\".to_string(), Value::from(true));"));
			sList.add(new Statement(serial+28000L,3,"map.insert("));
			sList.add(new Statement(serial+29000L,4,"\"rows\".to_string(),"));
			sList.add(new Statement(serial+30000L,4,"Value::from(\"\"),"));
			sList.add(new Statement(serial+31000L,3,");"));
			sList.add(new Statement(serial+32000L,3,""));
			sList.add(new Statement(serial+33000L,3,"let resultjson = serde_json::to_string_pretty(&map).unwrap();"));
			sList.add(new Statement(serial+35000L,3,"return resultjson;"));
			sList.add(new Statement(serial+36000L,2,"}"));
			sList.add(new Statement(serial+37000L,1,"}"));
			
			method.setMethodStatementList(WriteableUtil.merge(sList));		
			return method;
		}
	}

	@Override
	public JavascriptBlock generateEasyUIJSButtonBlock() throws Exception {
		return null;
	}

	@Override
	public JavascriptMethod generateEasyUIJSActionMethod() throws Exception {
		if (this.denied) return null;
		else {
			Domain domain = this.domain;
			JavascriptMethod method = new JavascriptMethod();
			method.setSerial(200);
			method.setStandardName(StringUtil.lowerFirst(this.getVerbName()));
			
			List<Writeable> sList = new ArrayList<Writeable>();

			sList.add(new Statement(1000L,1,"if (isBlank($(\"#ff\").find(\"#"+this.domain.findFieldByFixedName("userName").getLowerFirstFieldName()+"\").val())){"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sList.add(new Statement(2000L,2,"$.messager.alert(\"Error\",\"Field "+this.domain.findFieldByFixedName("userName").getText() +"is empty.\",\"error\");"));
			} else {
				sList.add(new Statement(2000L,2,"$.messager.alert(\"错误\",\"必须字段"+this.domain.findFieldByFixedName("userName").getText()+"为空！\",\"error\");"));
			}
			sList.add(new Statement(3000L,2,"return;"));
			sList.add(new Statement(4000L,1,"}"));
			sList.add(new Statement(5000L,1,"$.ajax({"));
			sList.add(new Statement(6000L,2,"type: \"post\","));
			sList.add(new Statement(7000L,2,"url: \"../"+ this.domain.getControllerPackagePrefix()+"profile"+this.domain.getControllerNamingSuffix()+"/"+StringUtil.lowerFirst(this.getVerbName())+"\","));
			sList.add(new Statement(8000L,2,"data: JSON.stringify({"));
			
			long serial = 9000L;
			Set<Field> normalFields = new TreeSet<>(new FieldSerialComparator());
			normalFields.addAll(domain.getFieldsWithoutIdAndActive());
			Set<Field> deniedFields = new TreeSet<>(new FieldSerialComparator());
			deniedFields.add(this.domain.findFieldByFixedName("password"));
			deniedFields.add(this.domain.findFieldByFixedName("salt"));
			deniedFields.add(this.domain.findFieldByFixedName("loginFailure"));
			normalFields = FieldUtil.filterDeniedFields(normalFields,deniedFields);
			for (Field f: normalFields){
				if (f instanceof Dropdown) {
					sList.add(new Statement(serial, 3, f.getLowerFirstFieldName() + ":parseIntNeg($(\"#ff\").find(\"#"
							+ f.getLowerFirstFieldName() + "\").combobox(\"getValue\")),"));
				} else if (f.getFieldType().equalsIgnoreCase("bool")) {
					sList.add(new Statement(serial, 3,
							f.getLowerFirstFieldName() + ":parseBoolean($(\"#ff\").find(\"input[name='"
									+ f.getLowerFirstFieldName() + "']:checked\").val()),"));
				}  else if (f.getFieldType().equalsIgnoreCase("i32")||f.getFieldType().equalsIgnoreCase("i64")) {
					sList.add(new Statement(serial, 3, f.getLowerFirstFieldName() + ":parseInt($(\"#ff\").find(\"#"
							+ f.getLowerFirstFieldName() + "\").val()),"));
				} else if (f.getFieldType().equalsIgnoreCase("f64")||f.getFieldType().equalsIgnoreCase("f32")) {
					sList.add(new Statement(serial, 3, f.getLowerFirstFieldName() + ":parseFloat($(\"#ff\").find(\"#"
							+ f.getLowerFirstFieldName() + "\").val()),"));
				} else if (f.isTextarea()) {
					sList.add(new Statement(serial, 3, f.getLowerFirstFieldName() + ":$(\"#ff\").find(\"#"
							+ f.getLowerFirstFieldName() + "\").val(),"));
				} else {
					sList.add(new Statement(serial, 3, f.getLowerFirstFieldName() + ":$(\"#ff\").find(\"#"
							+ f.getLowerFirstFieldName() + "\").val(),"));
				}
				serial+=1000;
			}
			if (this.domain.hasActiveField()) {
				sList.add(new Statement(serial,3, this.domain.getActive().getLowerFirstFieldName()+":parseBoolean($(\"#ff\").find(\"input[name='"+this.domain.getActive().getLowerFirstFieldName()+"']:checked\").val()),"));
			}
			
			sList.add(new Statement(serial+26000L,2,"}),"));
			sList.add(new Statement(serial+27000L,2,"dataType: 'json',"));
			sList.add(new Statement(serial+28000L,2,"contentType:\"application/json;charset=UTF-8\","));
			sList.add(new Statement(serial+29000L,2,"success: function(data, textStatus) {"));
			sList.add(new Statement(serial+30000L,3,"if (data.success) {"));
			sList.add(new Statement(serial+31000L,4,"$('#ff').form('clear');"));
			FindMyProfileUser find = new FindMyProfileUser(this.domain,null);
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sList.add(new Statement(serial+32000L,4,"$.messager.alert(\"Info\",\"Update "+this.domain.getText()+" profile succeed.\",\"info\");"));
				sList.add(new Statement(serial+32100L,4,StringUtil.lowerFirst(find.getVerbName())+"();"));
				sList.add(new Statement(serial+33000L,3,"} else if (data.success == false){"));
				sList.add(new Statement(serial+34000L,4,"$.messager.alert(\"Error\",\"Update "+this.domain.getText()+" profile failed.\",\"error\");"));
				sList.add(new Statement(serial+34100L,4,StringUtil.lowerFirst(find.getVerbName())+"();"));
			} else {
				sList.add(new Statement(serial+32000L,4,"$.messager.alert(\"信息\",\"更新用户资料成功！\",\"info\");"));
				sList.add(new Statement(serial+32100L,4,StringUtil.lowerFirst(find.getVerbName())+"();"));
				sList.add(new Statement(serial+33000L,3,"} else if (data.success == false){"));
				sList.add(new Statement(serial+34000L,4,"$.messager.alert(\"错误\",\"更新用户资料失败！\",\"error\");"));
				sList.add(new Statement(serial+34100L,4,StringUtil.lowerFirst(find.getVerbName())+"();"));
			}
			sList.add(new Statement(serial+35000L,3,"}"));
			sList.add(new Statement(serial+36000L,3,"},"));
			sList.add(new Statement(serial+37000L,2,"complete : function(XMLHttpRequest, textStatus) {"));
			sList.add(new Statement(serial+38000L,2,"},"));
			sList.add(new Statement(serial+39000L,2,"error : function(XMLHttpRequest,textStatus,errorThrown) {"));
			sList.add(new Statement(serial+40000L,3,"alert(\"Error:\"+textStatus);"));
			sList.add(new Statement(serial+41000L,3,"alert(errorThrown.toString());"));
			sList.add(new Statement(serial+42000L,2,"}"));
			sList.add(new Statement(serial+43000L,1,"});"));
			
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;	
		}
	}

	@Override
	public Method generateDummyDaoImplMethod() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
}
